package com.jyy.prefabricated.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.Pageable;
import com.jyy.prefabricated.dto.ResetPwdDto;
import com.jyy.prefabricated.dto.TrainingOrganizationDto;
import com.jyy.prefabricated.entity.SysUser;
import com.jyy.prefabricated.entity.TrainingOrganization;
import com.jyy.prefabricated.enums.UserTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.jwt.JwtTokenUtil;
import com.jyy.prefabricated.security.CustomUserDetailsService;
import com.jyy.prefabricated.service.SysUserService;
import com.jyy.prefabricated.service.TrainingOrganizationService;
import com.jyy.prefabricated.utils.UserUtils;
import com.jyy.prefabricated.vo.StudentExamScoreVo;
import com.jyy.prefabricated.vo.TrainingOrganizationBuyExamVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 机构
 *
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@RequestMapping("/api")
@RestController
public class TrainingOrganizationController {

    @Autowired
    private TrainingOrganizationService trainingOrganizationService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    /**
     * 新增机构
     *
     * @param dto
     * @return
     */
    @PostMapping("/training-organization")
    public AjaxResult insert(@Valid @RequestBody TrainingOrganizationDto dto) {
        log.info("Rest request to insert training-organization:{}", dto);
        int id = trainingOrganizationService.insert(dto);
        TrainingOrganization result = trainingOrganizationService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 机构登录（账号不存在注册后登录）
     *
     * @param dto
     * @return
     */
    @PostMapping("/training-organization-login")
    public AjaxResult insertLogin(@Valid @RequestBody TrainingOrganizationDto dto , HttpServletRequest request) {
        log.info("Rest request to insert training-organization:{}", dto);
        int id = trainingOrganizationService.insertLogin(dto);
       // SysUser user = sysUserService.selectById(id);
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(dto.getTel(), dto.getTel());
        UserDetails userDetails = customUserDetailsService.loadUserByUsername(dto.getTel());
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        // 将 authentication 存入 ThreadLocal，方便后续获取用户信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        return AjaxResult.success(result);
    }

    /**
     * 更新机构
     *
     * @param apply
     * @return
     */
    @PutMapping("/training-organization")
    public AjaxResult update(@Valid @RequestBody TrainingOrganizationDto apply) {
        log.info("Rest request to update training-organization:{}", apply);
        // 此处属于前端bug，目前已经修改
        trainingOrganizationService.update(apply);
        TrainingOrganization result = trainingOrganizationService.selectById(apply.getId());
        return AjaxResult.success(result);
    }
    /**
     * 判断机构手机号是否存在
     * @return
     */
    @GetMapping("/training-organization-tel/{id}/{tel}")
    public AjaxResult judgeTel(@PathVariable Integer id ,@PathVariable String tel) {

        trainingOrganizationService.judgeTel(id,tel);
        return AjaxResult.success();
    }

    /**
     * 修改接口
     *
     * @param apply
     * @return
     */
    @PutMapping("/students-official")
    public AjaxResult updateStudentsOfficial(@Valid @RequestBody TrainingOrganizationDto apply) {
        log.info("Rest request to update training-organization:{}", apply);
        // 此处属于前端bug，目前已经修改
        trainingOrganizationService.update(apply);
        TrainingOrganization result = trainingOrganizationService.selectById(apply.getId());
        return AjaxResult.success(result);
    }

    /**
     * 更新机构状态
     *
     * @param id
     * @return
     */
    @PutMapping("/training-organization-status/{id}")
    public AjaxResult updateStatus(@PathVariable Integer id) {
        log.info("Rest request to update training-organization-status:{}", id);
        int row = trainingOrganizationService.updateStatus(id);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 重置培训机构密码
     *
     * @param dto
     * @return
     */
    @PutMapping("/training-organization-pwd")
    public AjaxResult resetPwd(@RequestBody ResetPwdDto dto) {
        log.info("Rest request to reset training-organization-pwd:{}", dto);
        int row = trainingOrganizationService.resetTrainingOrganizationPwd(dto.getAccount(), dto.getPassword());
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 查询机构详情
     *
     * @param id
     * @return
     */
    @GetMapping("/training-organization/{id}")
    public AjaxResult selectById(@PathVariable Integer id) {
        log.info("Rest request to find training-organization by id:{}", id);
        TrainingOrganization result = trainingOrganizationService.selectById(id);
        return AjaxResult.success(result);
    }

    /**
     * 删除机构
     *
     * @param id
     * @return
     */
    @DeleteMapping("/training-organization/{id}")
    public AjaxResult deleteById(@PathVariable Integer id) {
        log.info("Rest request to delete training-organization by id:{}", id);
        int row = trainingOrganizationService.delete(id);
        if (row > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 获取所有机构地区列表
     *
     * @return
     */
    @GetMapping("/training-organization-area")
    public AjaxResult selectArea() {
        log.info("Rest request to find training-organization area");
        List<Map<String, Object>> result = trainingOrganizationService.findAreaList();
        return AjaxResult.success(result);
    }

    /**
     * 分页查询机构信息
     *
     * @param name            名称
     * @param province        省
     * @param city            市
     * @param status          状态
     * @param courseId        课程id
     * @param coursePackageId 课程包id
     * @param projectId       项目id
     * @param pageable        分页信息
     * @return
     */
    @GetMapping("/training-organization")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String name, @RequestParam(required = false, defaultValue = "") String province, @RequestParam(required = false, defaultValue = "") String city, @RequestParam(required = false) Integer status, @RequestParam(required = false) Integer courseId, @RequestParam(required = false) Integer coursePackageId, @RequestParam(required = false) Integer projectId, Pageable pageable) {
        log.info("Rest request to find training-organization by params name:{},status:{},province:{},city:{},courseId:{},coursePackageId:{},projectId:{}", name, status, province, city, courseId, coursePackageId, projectId);
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<TrainingOrganization> trainingOrganizations = trainingOrganizationService.selectByParams(name, province, city, status, courseId, coursePackageId, projectId);
        PageInfo<TrainingOrganization> result = new PageInfo<>(trainingOrganizations);
        return AjaxResult.success(result);
    }

    /**
     * 查询机构信息
     *
     * @param name            名称
     * @param province        省
     * @param city            市
     * @param status          状态
     * @param courseId        课程id
     * @param coursePackageId 课程包id
     * @param projectId       项目id
     * @return
     */
    @GetMapping("/training-organization-list")
    public AjaxResult selectByParams(@RequestParam(required = false, defaultValue = "") String name, @RequestParam(required = false, defaultValue = "") String province, @RequestParam(required = false, defaultValue = "") String city, @RequestParam(required = false) Integer status, @RequestParam(required = false) Integer courseId, @RequestParam(required = false) Integer coursePackageId, @RequestParam(required = false) Integer projectId) {
        log.info("Rest request to find training-organization by params name:{},status:{},province:{},city:{},courseId:{},coursePackageId:{},projectId:{}", name, status, province, city, courseId, coursePackageId, projectId);
        List<TrainingOrganization> result = trainingOrganizationService.selectByParams(name, province, city, status, courseId, coursePackageId, projectId);
        return AjaxResult.success(result);
    }


    /**
     * 分页查询企业已购买考试列表
     *
     * @param pageable 分页信息
     * @return
     */
    @GetMapping("/training-organization-buy-exam")
    public AjaxResult selectBuyExam(Pageable pageable) {

        SysUser user = userUtils.getCurrentUser();

        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());

        List<TrainingOrganizationBuyExamVo> trainingOrganizationBuyExamVo = new ArrayList<>();
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            trainingOrganizationBuyExamVo = trainingOrganizationService.selectBuyExam(user.getTrainingOrganization().getId(), user.getId());
        }
        PageInfo<TrainingOrganizationBuyExamVo> result = new PageInfo<>(trainingOrganizationBuyExamVo);
        return AjaxResult.success(result);
    }

    /**
     * 分页查询企业学员考试记录
     *
     * @param pageable 分页信息
     * @return
     */
    @GetMapping("/training-organization-record")
    public AjaxResult selectTrainingOrganizationStudentExamRecord(@RequestParam(required = false, defaultValue = "") Integer examId, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());

        SysUser user = userUtils.getCurrentUser();
        List<StudentExamScoreVo> studentExamVoList = new ArrayList<>();
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            studentExamVoList = trainingOrganizationService.selectExamRecord(examId, user.getTrainingOrganization().getId());
        }
        PageInfo<StudentExamScoreVo> result = new PageInfo<>(studentExamVoList);
        return AjaxResult.success(result);
    }

}
